package test.lyj;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import json.ListMyCurvesObj;
import json.CurveObj;
import org.json.JSONException;
import test.lyj.model.DrawCurveView;
import test.lyj.model.ListAdapter;
import test.lyj.model.CurveNetThread;
import test.lyj.model.ShowCurveDetailNetThread;
import test.lyj.tool.Jsonformat2Bean;
import test.lyj.tool.Tool;
import test.lyj.ui.MyTab;
import test.lyj.ui.MyTab.OnTabClickListener;
import test.lyj.ui.MyTabMember;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LogonFrameActivity extends Activity {
    private MyTab mTabs;
    private DrawCurveView drawCurve;
    private float[] fdbx = new float[]{2, 5, 11, 17, 23, 28, 35, 41, 48, 60,
            71, 82, 93, 114, 135, 150};
    private float[] fx = null;
    
    private float ratiof = 0.0f;
	private float zoommax = 2.0f;
	private float zoommin = -0.8f;

	// 屏幕宽高
	private int display_w;
	private int display_h;

    public void onCreate(Bundle savedInstanceState) {
        //要接受从别的界面传过来的数据,必须在super.onCreate(savedInstanceState); 之前处理
        String pageParas = null;
        if (getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                pageParas = bundle.getString("myPara_msg");
                Log.d("LogonFrameActivity", "界面获得的参数:" + pageParas);
            }
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.curveindex_window);

        drawCurve = (DrawCurveView) findViewById(R.id.img_view);
        reflashImg();
       // Tool.showMsgDialog(this, String.valueOf(drawCurve.getmBitmap().getHeight()));
      //  ImageView hiddenView=(ImageView) findViewById(R.id.img_hidden);
      //  hiddenView.setImageBitmap(drawCurve.getmBitmap());
        findViewById(R.id.btn_zoomin).setOnClickListener(zoominClicker);
        findViewById(R.id.btn_zoomout).setOnClickListener(zoomoutClicker);

//		setTitle("电子名片-我的名片");
        mTabs = (MyTab) this.findViewById(R.id.myTab);
        mTabs.setChooseTabId(0);
        mTabs.addTabMember(new MyTabMember(1, "我的名片", R.drawable.fmp));
        mTabs.addTabMember(new MyTabMember(2, "名片夹", R.drawable.fmp));
        mTabs.addTabMember(new MyTabMember(3, "备份恢复", R.drawable.bf));
        mTabs.addTabMember(new MyTabMember(4, "消息中心", R.drawable.fmp));
        mTabs.addTabMember(new MyTabMember(5, "设置", R.drawable.sz));

        mTabs.setOnTabClickListener(new OnTabClickListener() {

            public void onTabClick(int tabId) {// 实现点击事件 75
                if (tabId == 1) {

                } else if (tabId == 2) {
                    Intent i = new Intent();
                    //i.setClass(MyCard.this, Inbox.class);
                    //startActivity(i);
                } else if (tabId == 3) {
                    Intent i = new Intent();
//					i.setClass(MyCard.this, Backup.class);
//					startActivity(i);
//					MyCard.this.finish();
                } else if (tabId == 4) {

                } else if (tabId == 5) {
                    Intent i = new Intent();
//					i.setClass(MyCard.this, PersonalSet.class);
//					startActivity(i);
//					MyCard.this.finish();
                }
            }
        });

        //显示主界面上面部分的内容
        ListView listView = (ListView) findViewById(R.id.lv_inlist);
        try {
            ListMyCurvesObj lobj = (ListMyCurvesObj) Jsonformat2Bean.formatJsonStr2Bean(pageParas);
            if (Tool.DEBUG) {
                Log.d("LogonFrameActivity", "curve array size:" + (lobj.getCurveArray() == null ? "null" : lobj.getCurveArray().length));
            }
               //     ArrayList temp=Tool.getStaticMap(this,0,20);
            ArrayList temp = suitListValues(this,lobj);
            ListAdapter listAdapter = new ListAdapter(LogonFrameActivity.this, temp, R.layout.list_base_window_item, new String[]{"icon", "name", "address"}, new int[]{R.id.item_image, R.id.item_name, R.id.item_address},messageListener);
            listView.setAdapter(listAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        ArrayList temp=Tool.getStaticMap(this,0,20);


        listView.setOnItemClickListener(new OnItemClickListener() {


            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                LinearLayout itemLayout=(LinearLayout)arg1;
				TextView addressView= (TextView) itemLayout.findViewById(R.id.item_address);
                Log.d("LogonFrameActivity",String.valueOf(addressView.getText()));
               // Tool.showMsgDialog(LogonFrameActivity.this, arg3 + "有戏？" + arg2);
                Map<String,String> paramap=new HashMap<String,String>();
			paramap.put("op", "viewmycurve");
			//paramap.put("username", URLEncoder.encode(usernameview.getText().toString()));
			paramap.put("username", Tool.username);
			paramap.put("psw", Tool.psw);
			paramap.put("id", String.valueOf(addressView.getText()));
//			paramap.put("psw", pswview.getText().toString());
//			Log.d("LogonActivity", "提交的参数:username:"+usernameview.getText().toString()+"|psw:"+pswview.getText().toString());
			//线程的启动方法在NetThread 的构造函数中
			new ShowCurveDetailNetThread(LogonFrameActivity.this,messageListener,paramap,null);
            }
        });
    }

    View.OnClickListener zoominClicker = new View.OnClickListener() {


		public void onClick(View v) {
			Animation animation = (AnimationSet) AnimationUtils.loadAnimation(LogonFrameActivity.this, R.anim.anim_set);
            animation.setFillAfter(true);
            animation.setFillBefore(false);
            drawCurve.setAnimation(animation);

        }
	};

    View.OnClickListener zoomoutClicker = new View.OnClickListener() {


		public void onClick(View v) {
			
//			Animation animation = (AnimationSet) AnimationUtils.loadAnimation(LogonFrameActivity.this, R.anim.anim_set);
//            drawCurve.setAnimation(animation);

        }
	};
    Handler messageListener = new Handler() {
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			String netresult = b.getString(Tool.TIMER_TASK_RESULT);
			switch (msg.what) {
			case 200://接收BUTTON中传送过来的消息
				Tool.showMsgDialog(LogonFrameActivity.this, "按钮事件:"+netresult);
				break;
			case Tool.TIMER_TASK_TIMEOUT:
				Tool.showMsgDialog(LogonFrameActivity.this, "线程超时"+netresult);
				break;
			case Tool.TIMER_TASK_COMPELETE:

				//Tool.showMsgDialog(LogonFrameActivity.this,"网络结果:"+netresult);
				try {
					//NormalObject object=(NormalObject) Jsonformat2Bean.formatJsonStr2Bean(netresult);
                    Log.d("curveObj",netresult);
                 CurveObj curveObj= (CurveObj) Jsonformat2Bean.formatJsonStr2Bean(netresult);
                    Log.d("curveObj","from json:"+curveObj);
                    drawCurve.setCurveObj(curveObj);
                    reflashImg();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Tool.showMsgDialog(LogonFrameActivity.this,"错误:"+e.getMessage());
				}
				break;

			}
			super.handleMessage(msg);
		}
	};

    private ArrayList<HashMap<String,Object>> suitListValues(LogonFrameActivity c, ListMyCurvesObj lobj) {
        ArrayList<HashMap<String,Object>> temp=new ArrayList();

        for (int i = 0; i < lobj.getCurveArray().length; i++) {
            CurveObj curve=lobj.getCurveArray()[i];

            HashMap<String, Object> testDataMap=new HashMap<String, Object>();
		testDataMap.put("name", curve.getTitle());
		testDataMap.put("address", curve.getSysId());
		Bitmap ic;
		if (i%2==0) {
			ic = BitmapFactory
                    .decodeResource(c.getResources(), R.drawable.icon);
		}else{
			ic = BitmapFactory.decodeResource(c.getResources(),R.drawable.line);

		}
		testDataMap.put("icon", ic);
		temp.add(testDataMap);
		}
		return temp;
    }

    private void reflashImg() {
        Log.d("Mysecondpaint===", "calculate");
        /*float a = Float.parseFloat(String.valueOf(atv.getText()));
          float b = Float.parseFloat(String.valueOf(btv.getText()));
          float c = Float.parseFloat(String.valueOf(ctv.getText()));*/
        float a = 80;
        float b = 50;
        float c = (float) 0.09;
        float[] fy = calculate(a, b, c);
        drawCurve.setFx(fx);
        drawCurve.setFy(fy);
        drawCurve.invalidate();
    }

    private float[] calculate(float a, float b, float c) {
        NumberFormat format = new DecimalFormat("#.##");
        float[] fy = new float[fdbx.length];
        fx = new float[fdbx.length];
        for (int i = 0; i < fdbx.length; i++) {
            // double s=Math.pow(Math.E, -0.04*(fx[i]/20));
            // //s=ForDight(s, 10);
            // String str=format.format(s);
            double result = a - (b * (Math.pow(Math.E, -c * (fdbx[i]))));
            fx[i] = fdbx[i];
            fy[i] = Float.parseFloat(format.format((result)));
            Log.d("calculate fx,fy", "i,fx,fy,c*fx,b*math,math=" + i + "/"
                    + fx[i] + "|" + fy[i] + "|" + String.valueOf(result));

        }

        return fy;
    }


}
